package com.ruoyi.web.controller.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.ByWxUser;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.domain.WxLoginInfo;
import com.ruoyi.system.service.IByCodeMsgService;
import com.ruoyi.system.service.IByWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 鉴权服务
 */
@RestController
@RequestMapping("/wx/auth")
@Validated
public class WxAuthController {

   /* private static WxMaService wxService;*/

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private IByWxUserService userService;


    @Autowired
    private IByCodeMsgService codeMsgService;


    @PostMapping("/qWxUserById")
    public Object qWxUserById(@RequestBody String param){
        String id = JSONObject.parseObject(param).getString("id");
        if(!StringUtils.isEmpty(id)){
            ByWxUser user = userService.selectByWxUserById(id);
            return AjaxResult.success(user);
        }

        return AjaxResult.success();
    }

    @PostMapping("/login_by_user")
    public Object loginByUser(@RequestBody String param, HttpServletRequest request){
        JSONObject json = JSONObject.parseObject(param);
        String nickname = json.getString("nickname");
        String password = json.getString("password");

        JSONObject resultJson = new JSONObject();

        ByWxUser newUser = userService.queryByOid(nickname);
        if(newUser == null){
            resultJson.put("code","400");
            resultJson.put("msg","The user was not found！");
            return AjaxResult.success(resultJson);
        }
        String pwd = Md5Utils.hash(password);
        if(!pwd.equals(newUser.getPassword())){
            resultJson.put("code","400");
            resultJson.put("msg","The user name or password is incorrect！");
            return AjaxResult.success(resultJson);
        }

        resultJson.put("code","200");
        resultJson.put("userInfo", newUser);
        return AjaxResult.success(resultJson);
    }


    /**
     * 微信登录
     *
     * @param request     请求对象
     * @return 登录结果
     */
    @PostMapping("login_by_weixin")
    public Object loginByWeixin(@RequestBody String param, HttpServletRequest request) {
        JSONObject json = JSONObject.parseObject(param);

        /*System.out.println(param);
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if (code == null || userInfo == null) {
            return AjaxResult.error("用户信息在传输过程中可能丢失了！");
        }*/

        /*String sessionKey = null;
        String openId = null;
        try {
//            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            return AjaxResult.error();//ResponseUtil.fail();
        }*/
        String nickname = json.getString("nickname");
        String password = json.getString("password");
        String mobile = json.getString("mobile");


        ByWxUser user = userService.queryByOid(nickname);
        if (user == null) {
            user = new ByWxUser();
            String id = IdUtils.fastUUID();
            user.setId(id);
            user.setUsername(nickname);
            user.setPassword(Md5Utils.hash(password));
            user.setWeixinOpenid(nickname);
            user.setMobile(mobile);
            user.setUserLevel("0");
            user.setStatus("0");
            user.setLastLoginTime(DateUtils.getTime());
            user.setLastLoginIp(IpUtils.getIpAddr(request));
            user.setAddTime(DateUtils.getTime());
            user.setUpdateTime(DateUtils.getNowDate());

            userService.insertByWxUser(user);
        } else {
            user.setLastLoginTime(DateUtils.getTime());
            user.setLastLoginIp(IpUtils.getIpAddr(request));
            if (userService.updateByWxUser(user) == 0) {
                return AjaxResult.error("更新失败");
            }
        }

        // token
//        String token = UserTokenManager.generateToken(user.getId());
        ByWxUser newUser = userService.queryByOid(user.getWeixinOpenid());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("userInfo", newUser);
        return AjaxResult.success(result);
    }


    @PostMapping("getcode")
    public Object getCode(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        String mobile = json.getString("mobile");
        // System.out.println(mobile);

        JSONObject rjson = codeMsgService.sendCode(mobile);

        return AjaxResult.success(rjson);
    }
}
